<template>
	<!-- 个人中心模块 -->
	<view class="user-page" :style="colorStyle">
		<template v-if="userInfo && isObjectData(diyData)">
			<view class="user_info" @click="router('/pages/users/user_info/index')">
				<image :src="userInfo.avatar" class="avatar"></image>
				<view class="info_view">
					<view class="name">{{ userInfo.nickname }}</view>
					<view class="label" v-if="userInfo.user_identity">{{userInfo.user_identity}}</view>
				</view>
				<image src="@/static/images/edit.png" class="edit"></image>
			</view>
			<view class="user_tabs">
				<view class="user_tabs_view">
					<view class="tabs_item" @click="router('/pages/goods/order_list/index')">
						<image src="@/static/images/t1.png"></image>
						<text>我的订单</text>
					</view>
					<view class="tabs_item" @click="router('/pages/users/user_coupon/index')">
						<image src="@/static/images/t2.png"></image>
						<text>优惠券</text>
					</view>
					<view class="tabs_item" @click="router('/pages/users/user_goods_collection/index')">
						<image src="@/static/images/t3.png"></image>
						<text>我的收藏</text>
					</view>
					<view class="tabs_item" @click="router('/pages/book/followStore')">
						<image src="@/static/images/t4.png"></image>
						<text>关注店铺</text>
					</view>
				</view>
			</view>

			<!-- <user-order-static v-if="isObjectData(orderAdminData) && orderAdminData.order.user_order"
				:orderAdminData="orderAdminData.order" :orderStaticData="diyData.orderStatic"></user-order-static>
			<user-poster :posterData="diyData.poster"></user-poster> -->
			<user-menu :menuData="diyData.menu" :routineContact='routineContact'></user-menu>
			<!-- <user-mer-menu v-if="diyData.merMenu.list.length" :merMenuData="diyData.merMenu"></user-mer-menu> -->
			<!-- <user-store-menu v-if="diyData.storeMenu.list.length" :storeMenuData="diyData.storeMenu"></user-store-menu> -->
			
		</template>
		
		
		<view class="fixed-lt bg-w111-000-s111-80 w-full h-full z-999" v-show="isextension" @touchmove.stop.prevent>
		</view>
		<pageFooter :style="colorStyle"></pageFooter>
		<ewcomerPop v-if="isComerGift" :comerGift="comerGift" @comerPop="comerPop"></ewcomerPop>
		<!-- #ifdef MP -->
		<editUserModal :isShow="editModal" @closeEdit="closeEdit" @editSuccess="editSuccess"></editUserModal>
		<!-- #endif -->
	</view>
</template>
<script>
	import {
		storeCardApi
	} from '@/api/store.js';
	import {
		newcomerGift
	} from '@/api/activity.js';
	import {
		copyRight
	} from '@/api/api.js';
	import {
		getMenuList,
		getUserInfo,
		setVisit,
		updateUserInfo,
		getRandCode,
		updateWechatInfo,
		getMenuData
	} from '@/api/user.js';
import {
    
} from '@/api/public.js';
	import {
		toLogin
	} from '@/libs/login.js';
	import {
		mapState,
		mapGetters
	} from 'vuex';
	// #ifdef H5
	import Auth from '@/libs/wechat';
	// #endif
	import {
		HTTP_REQUEST_URL
	} from '@/config/app';
	const app = getApp();
	import ewcomerPop from '@/components/ewcomerPop/index.vue';
	import pageFooter from '@/components/pageFooter/index.vue';
 
	import colors from '@/mixins/color';
	// #ifdef MP
	import editUserModal from '@/components/eidtUserModal/index.vue';
	// #endif
	import userMenu from './components/menus/index.vue';
 

	export default {
		components: {
			userMenu,
			pageFooter,
			ewcomerPop,
			// #ifdef MP
			editUserModal
			// #endif
		},
		computed: {
			...mapGetters({
				cartNum: 'cartNum',
				isLogin: 'isLogin'
			})
		},
		filters: {},
		mixins: [colors],
		provide() {
			return {
				tapQrCode: this.tapQrCode,
				bindPhone: this.bindPhone,
				intoPage: this.intoPage,
				goMenuPage: this.goMenuPage,
				getMenuData: this.getMenuData,
				goEdit: this.goEdit
			};
		},
		data() {
			return {
				diyData: {},
				orderAdminData: {},
				// #ifdef MP
				getHeight: this.$util.getWXStatusHeight(),
				// #endif
				vipStatus: 0,
				stu: false,
				orderMenu: [{
						icon: '',
						title: '待付款',
						url: '/pages/goods/order_list/index?status=0'
					},
					{
						icon: '',
						title: '待发货',
						url: '/pages/goods/order_list/index?status=1'
					},
					{
						icon: '',
						title: '待收货',
						url: '/pages/goods/order_list/index?status=2'
					},
					{
						icon: '',
						title: '待评价',
						url: '/pages/goods/order_list/index?status=3'
					},
					{
						icon: '',
						title: '售后/退款',
						url: '/pages/users/user_return_list/index'
					}
				],
				imgUrls: [],
				orderStatusNum: {},
				userInfo: '',
				showStatus: 1,
				routineContact: 0,
				// #ifdef H5 || MP
				pageHeight: '100%',
				// #endif
				// #ifdef APP-PLUS
				pageHeight: app.globalData.windowHeight,
				// #endif
				// #ifdef H5
				isWeixin: Auth.isWeixin(),
				//#endif
				footerSee: false,
				member_style: 1,
				my_banner_status: 1,
				menu_status: 1,
				service_status: 1,
				newcomer_status: 1,
				isextension: false,
				extension: {
					code: '',
					size: 380, // 二维码大小
					level: 3, //等级 0～4
					bgColor: '#FFFFFF', //二维码背景色 默认白色
					color: ['#333', '#333'] //边框颜色支持渐变色
				},
				imgHost: HTTP_REQUEST_URL,
				copyRightText: '',
				copyRightImg: '',
				giftPic: '',
				vip_type: 1,
				newcomer_style: 1,
				newList: [],
				newBg: '',
				comerGift: {},
				isComerGift: false,
				memberStatus: 0,
				balanceStatus: 0, // 余额是否展示
				editModal: false, // 编辑头像信息
				isScrolling: false,
				orderStyle: {
					1: ['icon-ic_daifukuan12', 'icon-ic_daifahuo11', 'icon-ic_daishouhuo1', 'icon-ic_daipingjia1',
						'icon-ic_daituikuan1'
					],
					2: ['icon-ic_daifukuan2', 'icon-ic_daifahuo2', 'icon-ic_daishouhuo2', 'icon-ic_daipingji2',
						'icon-ic_daituikuan2'
					],
					3: ['icon-ic_daifukuan', 'icon-ic_daifahuo', 'icon-ic_daishouhuo', 'icon-ic_daipingjia',
						'icon-ic_daituikuan'
					]
				},
				codeImg: ''
			};
		},
		created() {
			let that = this;
			// #ifdef MP
			// 小程序静默授权
			if (!this.$store.getters.isLogin) {
				// Routine.getCode()
				//   .then(code => {
				//     Routine.silenceAuth(code).then(res => {
				//       this.onLoadFun();
				//     })
				//   })
				//   .catch(res => {
				//     uni.hideLoading();
				//   });
			}
			// #endif
			// #ifdef APP-PLUS
			that.$set(that, 'pageHeight', app.globalData.windowHeight);
			// #endif
		},
		async onLoad(option) {
			if (this.isLogin) {
				// this.getNewcomerGift();
			}
			// #ifdef H5
			if (this.isLogin && Auth.isWeixin() && option.code) {
				try {
					let res = await updateWechatInfo({
						code: option.code
					});
					this.userInfo.nickname = res.data.nickname;
					this.userInfo.avatar = res.data.avatar;
					this.userInfo.is_complete = 1;
				} catch (e) {}
			}
			// #endif
			this.colorData();
		},
		onReady() {},
		onShow() {
			uni.removeStorageSync("store_id")
			if (!this.isLogin) {
				this.userInfo = '';
				toLogin();
				return;
			}
			if (this.cartNum > 0) {
				uni.setTabBarBadge({
					index: 3,
					text: this.cartNum > 99 ? '99+' : this.cartNum + ''
				});
			} else {
				uni.hideTabBarRedDot({
					index: 3
				});
			}
			this.copyRightText = uni.getStorageSync('copyNameInfo');
			this.copyRightImg = uni.getStorageSync('copyImageInfo');
			uni.removeStorageSync('form_type_cart');
			if (!this.copyRightText) {
				this.getCopyRight();
			}
			let that = this;
			// #ifdef APP-PLUS
			uni.getSystemInfo({
				success: function(res) {
					that.pageHeight = res.windowHeight + 'px';
				}
			});
			// #endif
			if (that.isLogin) {
				this.getUserInfo();
				this.getMyMenus();
				this.setVisit();
				this.getMenuData();
			}
		},
		// #ifdef MP || APP-PLUS
		onPageScroll(e) {
			if (e.scrollTop > 50) {
				this.isScrolling = true;
			} else if (e.scrollTop < 50) {
				this.isScrolling = false;
			}
		},
		// #endif
		methods: {
			router(url) {
				uni.navigateTo({
					url
				})
			},
			hello(res) {
				this.codeImg = res.img.tempFilePath;
			},
			downloadCode() {
				let that = this
				// #ifdef H5
				var canvas = document.getElementById("hah").getElementsByTagName("canvas")
				var imgURL = canvas[0].toDataURL("image/png")
				var dlLink = document.createElement('a');
				dlLink.download = "店员推广码";
				dlLink.href = imgURL;
				dlLink.dataset.downloadurl = ["image/png", dlLink.download, dlLink.href].join(':');
				document.body.appendChild(dlLink);
				dlLink.click();
				document.body.removeChild(dlLink);
				// #endif
				// #ifdef MP
				uni.downloadFile({
					url: that.extension.code,
					success: (res) => {
						if (res.statusCode === 200) {
							uni.saveImageToPhotosAlbum({
								filePath: res.tempFilePath,
								success: function(res) {
									that.$util.Tips({
										title: '保存成功',
										icon: 'success'
									});
								},
								fail: function(res) {
									console.log(res)
									that.$util.Tips({
										title: '保存失败'
									});
								}
							});
						}
					}
				});
				// #endif
				// #ifdef APP-PLUS
				uni.saveImageToPhotosAlbum({
					filePath: that.codeImg,
					success: function(res) {
						that.$util.Tips({
							title: '保存成功',
							icon: 'success'
						});
					},
					fail: function(res) {
						that.$util.Tips({
							title: '保存失败'
						});
					}
				});
				// #endif
			},
			closeCode() {
				this.isextension = false
			},
			isObjectData(obj) {
				return Object.keys(obj).length !== 0;
			},
			// #ifdef MP
			editSuccess() {
				this.editModal = false;
				this.getUserInfo();
			},
			closeEdit() {
				this.editModal = false;
			},
			// #endif
			getCopyRight() {
				copyRight()
					.then((res) => {
						let data = res.data;
						if (!data.copyrightContext && !data.copyrightImage) {
							data.copyrightImage = '/static/images/support.png';
						}
						uni.setStorageSync('copyNameInfo', data.copyrightContext);
						uni.setStorageSync('copyImageInfo', data.copyrightImage);
						this.copyRightText = data.copyrightContext;
						this.copyRightImg = data.copyrightImage;
					})
					.catch((err) => {
						return this.$util.Tips({
							title: err.msg
						});
					});
			},
			// 查看订单
			intoPage(url) {
				if (this.isLogin) {
					if (['/pages/users/user_vip/index', '/pages/annex/vip_grade_active/index'].includes(url) && !this
						.userInfo.member_func_status) {
						this.$util.Tips({
							title: '会员卡功能暂未开启'
						});
					} else {
						this.$util.JumpPath(url);
					}
				} else {
					toLogin();
				}
			},
			// 编辑页面
			goEdit() {
				if (this.isLogin == false || !this.userInfo.uid) {
					toLogin();
				} else {
					// #ifdef MP
					if (this.userInfo.is_default_avatar) {
						this.editModal = true;
						return;
					}
					// #endif
					uni.navigateTo({
						url: '/pages/users/user_set/index'
					});
				}
			},
			goDetail(item) {
				uni.navigateTo({
					url: `/pages/goods_details/index?id=${item.id}&fromPage='newVip'`
				});
			},
			comerPop() {
				this.isComerGift = false;
			},
			getNewcomerGift() {
				if (uni.getStorageSync('newcomerGift')) {
					return (this.isComerGift = false);
				}
				newcomerGift()
					.then((res) => {
						this.comerGift = res.data;
						if (Object.prototype.toString.call(this.comerGift) == '[object Object]') {
							if (res.data.coupon_count || res.data.product_count || res.data.register_give_money || res
								.data.first_order_discount || res.data.register_give_integral) {
								uni.setStorageSync('newcomerGift', true);
								this.isComerGift = true;
							}
						}
					})
					.catch((err) => {
						return this.$util.Tips({
							title: err
						});
					});
			},
			tapQrCode() {
				uni.navigateTo({
					url: '/pages/users/user_member_code/index'
				});
			},
			getRoutineUserInfo(e) {
				updateUserInfo({
						userInfo: e.detail.userInfo
					})
					.then((res) => {
						this.getUserInfo();
						return this.$util.Tips('更新用户信息成功');
					})
					.catch((err) => {
						return this.$util.Tips(err);
					});
			},
			// 记录会员访问
			setVisit() {
				setVisit({
					url: '/pages/user/index'
				}).then((res) => {});
			},
			// 打开授权
			openAuto() {
				toLogin();
			},
			// 授权回调
			onLoadFun(e) {
				this.getUserInfo(e);
				this.getMyMenus();
				this.setVisit();
			},
			// 绑定手机
			bindPhone() {
				uni.navigateTo({
					url: '/pages/users/user_phone/index'
				});
			},
			// 获取行销数据
			getMenuData() {
				getMenuData().then((res) => {
					this.orderAdminData = res.data;
				});
			},
			/**
			 * 获取个人用户信息
			 */
			getUserInfo() {
				let that = this;
				getUserInfo().then((res) => {
					that.userInfo = res.data;
					that.stu = res.data.svip_open;
					that.balanceStatus = res.data.balance_func_status;
					that.memberStatus = parseInt(res.data.member_func_status);
					that.vipStatus = res.data.vip_status;
					that.$store.commit('SETUID', res.data.uid);
					that.$store.commit('UPDATE_USERINFO', res.data);
					that.orderMenu.forEach((item, index) => {
						switch (item.title) {
							case '待付款':
								this.$set(item, 'num', res.data.orderStatusNum.unpaid_count);
								break;
							case '待发货':
								this.$set(item, 'num', res.data.orderStatusNum.unshipped_count);
								break;
							case '待收货':
								this.$set(item, 'num', res.data.orderStatusNum.received_count);
								break;
							case '待评价':
								this.$set(item, 'num', res.data.orderStatusNum.evaluated_count);
								break;
							case '售后/退款':
								this.$set(item, 'num', res.data.orderStatusNum.refunding_count);
								break;
						}
					});
				});
			},
			getMyMenus: function() {
				let that = this;
				getMenuList().then((res) => {
					this.diyData = res.data.diy_data;
					this.switchTab(this.diyData.order.style);
					this.my_banner_status = res.data.diy_data.my_banner_status;
					this.menu_status = res.data.diy_data.menu_status;
					this.service_status = res.data.diy_data.service_status;
					this.vip_type = res.data.diy_data.vip_type;
					this.newcomer_style = res.data.diy_data.newcomer_style;
					this.newcomer_status = res.data.diy_data.newcomer_status;
					this.imgUrls = res.data.routine_my_banner;
					this.routineContact = Number(res.data.routine_contact_type);
				});
			},
			switchTab(style) {
				this.orderMenu.forEach((item, index) => {
					item.icon = this.orderStyle[style][index];
				});
			},
			goMenuPage(url, name) {
				if (this.isLogin) {
					let arr = url.split('@APPID=');
					if (arr.length > 1) {
						//#ifdef MP
						uni.navigateToMiniProgram({
							appId: arr[arr.length - 1],
							path: arr[0],
							envVersion: 'release',
							success: (res) => {
								console.log('打开成功', res);
							},
							fail: (err) => {
								console.log('sgdhgf', err);
							}
						});
						//#endif
						//#ifndef MP
						this.Tips({
							title: 'h5与app端不支持跳转外部小程序'
						});
						//#endif
					} else {
						if (url == '/pages/extension/customer_list/chat' || url == 'https://chat.crmeb.net/chat/mobile') {
							this.$util.getCustomer(this.userInfo);
						} else {
							if (url.indexOf('http') === -1) {
								// #ifdef H5
								if (name && name === '订单核销') {
									return (window.location.href = `${location.origin}${url}`);
								}
								// #endif
								// #ifdef MP
								if (url != '#' && url == '/pages/users/user_set/index') {
									uni.openSetting({
										success: function(res) {}
									});
								}
								// #endif
								if (url == '/pages/store_spread/index') {
									storeCardApi()
										.then((res) => {
											this.isextension = true;
											this.$nextTick(function() {
												this.extension.code = res.data.url;
											});
										})
										.catch((err) => {
											uni.hideLoading();
											this.$util.Tips({
												title: err
											});
										});
								}
								if (
									['/pages/goods_cate/goods_cate', '/pages/order_addcart/order_addcart',
										'/pages/user/index', '/pages/store_cate/store_cate', '/pages/index/index'
									].indexOf(url) == -1
								) {
									uni.navigateTo({
										url: url
									});
								} else {
									uni.reLaunch({
										url: url
									});
								}
							} else {
								// #ifdef H5
								this.$util.JumpPath(url);
								// #endif
								// #ifndef H5
								uni.navigateTo({
									url: `/pages/annex/web_view/index?url=${url}`
								});
								// #endif
							}
						}
					}
				}
			}
		}
	};
</script>

<style lang="scss" scoped>
	/deep/.uni-badge-left-margin .uni-badge--error {
		background-color: var(--view-theme) !important;
	}

	.footer-placeholder {
		height: calc(98rpx+ constant(safe-area-inset-bottom));
		height: calc(98rpx + env(safe-area-inset-bottom));
		height: 98rpx;
	}

	.user-page {
		padding-bottom: calc(100rpx+ constant(safe-area-inset-bottom));
		padding-bottom: calc(100rpx + env(safe-area-inset-bottom));
		padding-bottom: 100rpx;
		// padding-top: var(--status-bar-height);
	}

	.copy_right {
		text-align: center;
		color: #ccc;
		font-size: 22rpx;
		margin-top: 40rpx;

		.copyRightImg {
			width: 219rpx;
			height: 74rpx;
			margin: 16rpx auto;
			display: block;
		}

		.support {
			width: 219rpx;
			height: 74rpx;
			margin: 54rpx auto;
			display: block;
		}

		.copyRightText {
			margin-top: 0rpx;
			color: #ccc;
			font-size: 20rpx;
			margin-bottom: 20rpx;
		}
	}

	.user_info {
		display: flex;
		align-items: center;
		padding: 40rpx 0 40rpx 32rpx;
		box-sizing: border-box;

		.avatar {
			width: 112rpx;
			height: 112rpx;
			border-radius: 50%;
		}

		.info_view {
			flex: 1;
			height: 112rpx;
			padding: 6rpx 12rpx;
			box-sizing: border-box;
			display: flex;
			flex-direction: column;
			justify-content: space-between;

			.name {
				font-size: 32rpx;
				color: #333333;
			}

			.label {
				width: 96rpx;
				height: 42rpx;
				font-size: 24rpx;
				color: #3A8FF9;
				background: rgba(255, 255, 255, 0.1);
				border-radius: 132rpx 132rpx 132rpx 132rpx;
				border: 2rpx solid #3A8FF9;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}

		.edit {
			width: 202rpx;
			height: 64rpx;
		}
	}

	.user_tabs {
		padding: 0 32rpx;
		box-sizing: border-box;

		.user_tabs_view {
			height: 170rpx;
			background: #FFFFFF;
			border-radius: 24rpx 24rpx 24rpx 24rpx;
			display: flex;
			justify-content: space-between;
		}

		.tabs_item {
			width: 25%;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;

			image {
				width: 64rpx;
				height: 64rpx;
			}

			text {
				font-weight: 500;
				font-size: 24rpx;
				color: #333333;
				margin-top: 8rpx;
			}
		}
	}
</style>